package com.example.emos.wx.config.shiro;

import com.example.emos.wx.db.pojo.TbUser;
import com.example.emos.wx.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;


/**
 * @ClassName OAuth2Realm
 * @Description TODO
 * @Author luowenhong
 * @Version 1.0
 **/

@Component
public class OAuth2Realm extends AuthorizingRealm {

    @Autowired
    private JwtTokenUtils jwtTokenUtils;

    @Autowired
    private UserService userService;

    @Override
    public boolean supports(AuthenticationToken token){
        return token instanceof OAuth2Token;
    }

    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        /** 查询用户的权限列表 */
        TbUser user = (TbUser) principals.getPrimaryPrincipal();
        Set<String> permission = userService.searchUserPermissions(user.getId());
        /** 把权限列表添加到info对象中 */
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permission);
        return info;
    }

    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        /** 从令牌中获取userId，然后检测该账户是否被冻结。 */
        String accessToken = (String) token.getPrincipal();
        Integer userId = jwtTokenUtils.getUserId(accessToken);
        TbUser user = userService.selectById(userId);
        if (user == null){
            throw new LockedAccountException("账号已被锁定,请联系管理员");
        }
        /** 往info对象中添加用户信息、Token字符串 */
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, accessToken, getName());
        return info;
    }

}
